import json

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.db import models
from django.core.serializers import serialize, deserialize
from django.db.models.query import QuerySet


class LoginRequiredMiXin(object):
    """
    登录状态的判定
    """
    @method_decorator(login_required(login_url="/users/login/"))
    def dispatch(self,request,*args,**kwargs):
        return super(LoginRequiredMiXin,self).dispatch(request, *args, **kwargs)


class MyJsonEncoder(json.JSONEncoder):
    """
    自定义实现对Model实例对象序列化  json.dumps(params,cls=MyJsonEncoder)

    serializers 只支持序列化 queryset集合对象
    encodedjson = serializers.serialize('json',guide)
    decodejson = serializers.deserialize(encodedjson)

    dumps,loads只能对List/Dict常见对象序列化,反序列化
    encodedjson = json.dumps(List)
    decodejson = json.loads(encodedjson)
    """
    def default(self,obj):
        if isinstance(obj,QuerySet): #serializer 只支持序列化 queryset集合对象,all()和filter()返回的结果
            return json.loads(serialize("json",obj))
        if isinstance(obj,models.Model):#处理当个对象
            return json.loads(serialize('json',[obj])[1:-1])
        if hasattr(obj,'isoformat'): # 处理日期类型
            return obj.isoformat()
        return json.JSONEncoder.default(self,obj)


def MyJsonDecode(json):
    """
    反序列化表单数据
    """
    if json[0] == '[':
        return deserialize('json', json)
    else:
        return deserialize('json', '[' + json + ']')